import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:puppy_store/main.dart';
import 'package:puppy_store/models/cart_model.dart';
import 'package:puppy_store/models/home_model.dart';
import 'package:puppy_store/pages/account/account_login_page.dart';
import 'package:puppy_store/pages/goods_detail/goods_detail_bottom_bar.dart';
import 'package:puppy_store/pages/home/widgets/loadingAnimation.dart';
import 'package:puppy_store/pages/order_payment/order_settlement_page.dart';
import 'package:puppy_store/service/cart_api.dart';
import 'package:puppy_store/utils/common_utils.dart';
import 'package:puppy_store/widgets/custom_image.dart';
import 'package:puppy_store/widgets/custom_refresher.dart';
import 'package:puppy_store/widgets/price_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

class CartPage extends StatefulWidget {
  const CartPage({this.isShowBack = false, super.key});
  // 是否展示返回按钮
  final bool isShowBack;

  @override
  _CartPageState createState() => _CartPageState();
}

class _CartPageState extends State<CartPage>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  @override
  bool get wantKeepAlive => true;

  // 是否展示Loading动效
  bool _isShowLoading = true;

  // 猜你细化商品列表
  List<GoodsModel> _userLike = [];

  // 获取猜你喜欢
  void _loadUserLike() async {
    try {
      List<GoodsModel> userLike = await CartApi.getUserLike(6);
      setState(() {
        _userLike = userLike;
      });
    } on DioException catch (e) {
      EasyLoading.showToast("获取猜你喜欢失败: ${e.response?.data['message']}");
    }
  }

  // 有效的购物车数据
  List<CartItemModel> _valids = [];

  // 侧滑控制器
  late final SlidableController _slidableController = SlidableController(this);

  // 刷新控制器
  late RefreshController _refreshController;

  // 标记token异常, 用来确定是否展示未登录界面
  bool _isTokenError = false;

  void _loadCartDate() async {
    try {
      CartModel cartModel = await CartApi.getCart();
      EasyLoading.showToast("获取数据陈功");
      _refreshController.refreshCompleted();
      setState(() {
        _valids = cartModel.valids!;
        _isShowLoading = false;
        _isTokenError = false;
      });
    } on DioException catch (e) {
      _refreshController.refreshFailed();
      EasyLoading.showToast("获取购物车数据失败: ${e.response?.data['message']}");
    }
  }

  // 计算购物车商品总数量
  int _getTotalCount() {
    int totalCount = 0;
    _valids.forEach((itemModel) {
      totalCount += itemModel.count;
    });
    return totalCount;
  }

  // 修改购物车
  void _updateCart(int index, CartItemModel itemModel) async {
    try {
      CartItemModel updateModel = await CartApi.updateCart(
        itemModel.skuId!,
        itemModel.count,
        itemModel.selected,
      );
      EasyLoading.showToast("修改成功");

      // 把修改后的商品数据转换到原数组中
      _valids[index] = updateModel;

      setState(() {});
      // 跨组件通信 步骤4: 在要更新的地方 通知ValueNotifier更新值, 局部刷新界面
      totalCountNotifier?.value = _getTotalCount();
    } on DioException catch (e) {
      EasyLoading.showToast("修改失败: ${e.response?.data['message']}");
    }
  }

  // 删除购物车
  void _deleteCart(CartItemModel itemModel) async {
    try {
      dynamic res = await CartApi.deleteCart(itemModel.skuId!);

      // 更新购物车列表
      _valids.remove(itemModel);
      debugPrint("删除成功 $_valids");
      setState(() {});

      EasyLoading.showToast("删除成功");

      // 跨组件通信 步骤4: 在要更新的地方 通知ValueNotifier更新值, 局部刷新界面
      totalCountNotifier?.value = _getTotalCount();
    } on DioException catch (e) {
      EasyLoading.showToast("删除失败: ${e.response?.data['message']}");
    }
  }

  // 获取全选状态
  bool _getSelectAllStatus() {
    bool ret = true;
    if (_valids.length != 0) {
      _valids.forEach((itemModel) {
        if (!itemModel.selected) {
          ret = false;
        }
      });
    } else {
      ret = false;
    }
    return ret;
  }

  // 全选/反选购物车
  void _selectAllCart(bool selected) async {
    try {
      dynamic res = await CartApi.selectAll(selected);
      debugPrint("全选成功 $res");
      setState(() {
        _valids.forEach((itemModel) {
          itemModel.selected = selected;
        });
      });
    } on DioException catch (e) {
      EasyLoading.showToast("全选失败: ${e.response?.data['message']}");
    }
  }

  // 计算选中商品的总价格
  double _getTotalPrice() {
    double totalPrice = 0.0;
    _valids.forEach((itemModel) {
      if (itemModel.selected) {
        // double.parse 转换字符串为小数
        totalPrice += itemModel.count * double.parse(itemModel.price!) * 100;
      }
    });
    return totalPrice / 100;
  }

  @override
  void initState() {
    // 获取购物车数据
    _loadCartDate();
    _loadUserLike();
    _refreshController = RefreshController();

    // 订阅获取购物车数据token异常事件
    eventBus.on<GetCartTokenError>().listen((event) {
      // 接收到事件后, 刷新购物车数据
      _isTokenError = true; // 标记token异常
      _isShowLoading = false; // 关闭Loading动效
      _refreshController.refreshFailed(); // 下拉刷新失效
      setState(() {});
    });

    // 订阅登录成功后事件
    eventBus.on<LoginSuccessEvent>().listen((event) {
      // 接收到事件后, 刷新购物车数据
      _isTokenError = false; // 标记token正常
      _isShowLoading = false; // 显示Loading动效
      _loadCartDate(); // 刷新购物车数据
      setState(() {});
    });

    super.initState();
  }

  @override
  void dispose() {
    // 销毁控制器
    _refreshController.dispose();
    super.dispose();
  }

  // 构建购物车内容
  Widget _builderCartContent() {
    // 如果Token异常,展示未登录界面
    if (_isTokenError) {
      return _buildToLogin();
    } else if (_valids.length == 0) {
      return _buildEmptyCart();
    } else {
      return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: _valids.length,
        itemBuilder: (BuildContext context, int index) {
          return _buildCartItem(index);
        },
      );
    }
  }

  /// 构建未登录界面
  Widget _buildToLogin() {
    return Padding(
      padding: EdgeInsets.only(
        left: 120.0,
        top: 30.0,
        right: 120.0,
        bottom: 20.0,
      ),
      child: GestureDetector(
        onTap: () {
          Navigator.push(
            context,
            CupertinoPageRoute(
              builder: (BuildContext context) {
                return AccountLoginPage();
              },
            ),
          );
        },
        child: Container(
          width: 120.0,
          height: 40.0,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(2.0),
            gradient: LinearGradient(
              colors: [Color(0xFF00D2AE), Color(0xFF00BD9A)],
            ),
          ),
          child: Text(
            '去登陆',
            style: TextStyle(color: Colors.white, fontSize: 14.0),
          ),
        ),
      ),
    );
  }

  Widget _buildEmptyCart() {
    return Padding(
      padding: EdgeInsets.only(top: 30.0, bottom: 20.0),
      child: GestureDetector(
        onTap: () {
          Navigator.popUntil(context, ModalRoute.withName('/'));
        },
        child: Column(
          children: [
            Image.asset('assets/gouwuchekong.png'),
            Text(
              '购物车是空的',
              style: TextStyle(color: Color(0xFF9EA1A3), fontSize: 14.0),
            ),
            Padding(
              padding: EdgeInsets.only(left: 120.0, top: 20.0, right: 120.0),
              child: GestureDetector(
                onTap: () {
                  // Navigator.popUntil(context, (route)=>true); //所有路由都删除
                  // Navigator.popUntil(context, (route)=>false); //所有路由不删除
                  if (widget.isShowBack) {
                    // 如果不是一级页面, 直接跳转到首页
                    Navigator.popUntil(context, ModalRoute.withName('/'));
                  } else {
                    // EventBus使用 步骤4: eventB如果是一级页面,使用EventBus传递事件
                    eventBus.fire(GoToHomeEvent());
                  }
                },
                child: Container(
                  width: 120.0,
                  height: 40.0,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(2.0),
                    gradient: LinearGradient(
                      colors: [Color(0xFF00D2AE), Color(0xFF00BD9A)],
                    ),
                  ),
                  child: Text(
                    '去逛逛',
                    style: TextStyle(color: Colors.white, fontSize: 14.0),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建删除对话框
  Widget _buildDeleteDialog(CartItemModel itemModel, GlobalKey slidKey) {
    return Center(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 30.0),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          color: Colors.white,
        ),
        clipBehavior: Clip.antiAlias,
        width: MediaQuery.of(context).size.width - 100.0,
        height: 138.0,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '是否确认删除此商品？',
              style: TextStyle(color: Color(0xFF333333), fontSize: 16.0),
            ),
            Padding(
              padding: EdgeInsets.only(top: 28.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: GestureDetector(
                      child: Container(
                        height: 40.0,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(2.0),
                          border: Border.all(color: Color(0xFF666666)),
                        ),
                        child: Text(
                          '取消',
                          style: TextStyle(
                            fontSize: 13.0,
                            color: Color(0xFF666666),
                          ),
                        ),
                      ),
                      onTap: () {
                        // 手动关闭左滑面板
                        slidKey.currentContext != null
                            ? Slidable.of(slidKey.currentContext!)?.close()
                            : null;
                        Navigator.of(context, rootNavigator: true).pop();
                      },
                    ),
                  ),
                  SizedBox(width: 16.0),
                  Expanded(
                    child: GestureDetector(
                      child: Container(
                        height: 40.0,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(2.0),
                          gradient: LinearGradient(
                            colors: [Color(0xff3CCEAF), Color(0xff27BA9B)],
                          ),
                        ),
                        child: Text(
                          '确认',
                          style: TextStyle(fontSize: 13.0, color: Colors.white),
                        ),
                      ),
                      onTap: () {
                        // 删除购物车
                        _deleteCart(itemModel);
                        // 刷新购物车
                        _loadCartDate();
                        // 关闭对话框
                        // 手动关闭左滑面板
                        //Slidable.of(slidKey.currentContext!)?.close(); // 只适用于与自动关闭的方式
                        _slidableController.close();
                        Navigator.of(context, rootNavigator: true).pop();
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建购物车item
  Widget _buildCartItem(int index) {
    CartItemModel itemModel = _valids[index];
    GlobalKey slidKey = GlobalKey(debugLabel: itemModel.skuId);
    return Container(
      margin: EdgeInsets.only(top: 10.0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(4.0),
      ),
      clipBehavior: Clip.antiAlias,
      padding: EdgeInsets.all(10.0),
      child: Slidable(
        // controller: _slidableController,
        key: slidKey, // 添加唯一标识方便后续控制
        endActionPane: ActionPane(
          motion: const DrawerMotion(),
          extentRatio: 0.5,
          children: [
            SlidableAction(
              // flex: 2, //设置占比
              onPressed: (BuildContext context) {},
              backgroundColor: const Color(0xFFFF9240), // 背景颜色
              foregroundColor: Colors.white, // 文字颜色
              autoClose: true, // 点击后是否自动收起
              label: "收藏",
            ),
            SlidableAction(
              // flex: 1, // 设置占比
              onPressed: (BuildContext context) {
                //展示删除购物车的对话框,自定义对话框样式
                showGeneralDialog(
                  context: context,
                  barrierDismissible: true, //点击遮罩是否消失
                  barrierLabel: "必传的文字提示", // 用于对弹框的说明,无实质意义
                  transitionDuration: Duration(milliseconds: 300), // 动画时间
                  pageBuilder: (
                    BuildContext context,
                    Animation<double> animation,
                    Animation<double> secondaryAnimation,
                  ) {
                    return _buildDeleteDialog(itemModel, slidKey);
                  },
                );
              },
              backgroundColor: Color(0xFFCF4444),
              autoClose: true,
              label: "删除",
            ),
          ],
        ),

        child: Row(
          children: [
            // 选择按钮
            GestureDetector(
              onTap: () {
                itemModel.selected = !itemModel.selected;
                _updateCart(index, itemModel);
              },
              child:
                  itemModel.selected
                      ? Image.asset('assets/check.png', gaplessPlayback: true)
                      : Image.asset(
                        'assets/uncheck.png',
                        gaplessPlayback: true,
                      ),
            ),
            // 商品信息：图片
            Padding(
              padding: EdgeInsets.only(left: 10.0),
              child: GestureDetector(
                onTap: () {},
                child: CustomImage(
                  url: itemModel.picture!,
                  width: 86.0,
                  height: 86.0,
                ),
              ),
            ),
            // 商品信息：商品名称 + 规格 + 价格和数量
            Expanded(
              child: Padding(
                padding: EdgeInsets.only(left: 10.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 商品名称
                    Text(
                      itemModel.name!,
                      style: TextStyle(
                        color: Color(0xFF262626),
                        fontSize: 13.0,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    // 规格
                    Padding(
                      padding: EdgeInsets.only(top: 6.0),
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          vertical: 2.0,
                          horizontal: 6.0,
                        ),
                        decoration: BoxDecoration(
                          color: Color(0xFFF7F7F8),
                          borderRadius: BorderRadius.circular(2.0),
                          border: Border.all(
                            color: Color(0xFFE4E4E4),
                            width: 0.5,
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          // 采用文本所需的最小宽度
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Container(
                              constraints: BoxConstraints(
                                maxWidth:
                                    MediaQuery.of(context).size.width - 196.0,
                              ),
                              child: Text(
                                itemModel.attrsText!,
                                style: TextStyle(
                                  color: Color(0xFF888888),
                                  fontSize: 11.0,
                                  height: 1.0,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            Padding(
                              padding: EdgeInsets.only(left: 6.0),
                              child: Image.asset('assets/arrow_down.png'),
                            ),
                          ],
                        ),
                      ),
                    ),
                    // 商品信息：价格和数量
                    Padding(
                      padding: EdgeInsets.only(top: 6.0),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          // 价格
                          PriceWidget(
                            price: itemModel.price!,
                            symbolFontSize: 12.0,
                            integerFontSize: 15.0,
                            decimalFontSize: 13.0,
                            color: Color(0xFFF10000),
                          ),
                          // 数量
                          Row(
                            children: [
                              Container(
                                width: 30.0,
                                height: 20.0,
                                child: GestureDetector(
                                  onTap: () {
                                    if (itemModel.count <= 1) {
                                      EasyLoading.showToast("商品数量不能小于1");
                                      return;
                                    }
                                    itemModel.count--;
                                    _updateCart(index, itemModel);
                                  },
                                  child: Image.asset(
                                    'assets/price_jian_on.png',
                                  ),
                                ),
                              ),
                              Container(
                                width: 40.0,
                                height: 20.0,
                                alignment: Alignment.center,
                                padding: EdgeInsets.symmetric(vertical: 2.0),
                                color: Color(0xFFF6F6F6),
                                child: Text(
                                  itemModel.count.toString(),
                                  style: TextStyle(
                                    color: Color(0xFF333333),
                                    fontSize: 13.0,
                                  ),
                                ),
                              ),
                              Container(
                                width: 30.0,
                                height: 20.0,
                                child: GestureDetector(
                                  onTap: () {
                                    itemModel.count++;
                                    _updateCart(index, itemModel);
                                  },
                                  child: Image.asset('assets/price_jia_on.png'),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建底部操作栏
  Widget _buildBottomBar() {
    // 底部操作栏的高度：自身高度 + 不规则屏幕底部间距
    return Container(
      height: 60.0 + MediaQuery.of(context).padding.bottom,
      color: Colors.white,
      child: Column(
        children: [
          Container(height: 1.0, color: Color(0xFFEDEDED)),
          Container(
            height: 59.0,
            padding: EdgeInsets.only(left: 20.0, right: 10.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        bool isSelectAll = _getSelectAllStatus();
                        _selectAllCart(!isSelectAll);
                      },
                      child: Row(
                        children: [
                          Container(
                            width: 18.0,
                            height: 18.0,
                            child:
                                _getSelectAllStatus()
                                    ? Image.asset(
                                      'assets/check.png',
                                      gaplessPlayback: true,
                                    )
                                    : Image.asset(
                                      'assets/uncheck.png',
                                      gaplessPlayback: true,
                                    ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(left: 6.0),
                            child: Text(
                              '全选',
                              style: TextStyle(
                                color: Color(0xFF1E1E1E),
                                fontSize: 13.0,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Padding(
                      padding: EdgeInsets.only(left: 20.0),
                      child: Row(
                        children: [
                          Text(
                            '合计: ',
                            style: TextStyle(
                              color: Color(0xFF1E1E1E),
                              fontSize: 13.0,
                            ),
                          ),
                          PriceWidget(
                            price: _getTotalPrice().toStringAsFixed(
                              2,
                            ), // 保留两位小数
                            symbolFontSize: 12.0,
                            integerFontSize: 20.0,
                            decimalFontSize: 18.0,
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                GestureDetector(
                  onTap: () {
                    // 判断是否至少选择一款上平
                    bool hasSettlementGoods = false;
                    _valids.forEach((CartItemModel itemModel) {
                      if (itemModel.selected) {
                        hasSettlementGoods = true;
                        return;
                      }
                    });
                    // 没有选择商品 阻断,并轻提示
                    if (!hasSettlementGoods) {
                      EasyLoading.showToast('请选择商品');
                      return;
                    }

                    Navigator.push(
                      context,
                      CupertinoPageRoute(
                        builder: (context) {
                          return OrderSettlementPage();
                        },
                      ),
                    );
                  },
                  child: Container(
                    width: 100.0,
                    height: 40.0,
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(2.0),
                      gradient: LinearGradient(
                        colors: [Color(0xff3CCEAF), Color(0xff27BA9B)],
                      ),
                    ),
                    child: Text(
                      '去结算',
                      style: TextStyle(fontSize: 13.0, color: Colors.white),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建猜你喜欢
  Widget _buildUserLike() {
    return StaggeredGridView.countBuilder(
      itemCount: _userLike.length,
      crossAxisCount: 2,
      crossAxisSpacing: 10.0,
      mainAxisSpacing: 10.0,
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return GestureDetector(
          onTap: () {},
          child: Container(
            padding: EdgeInsets.all(10.0),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(4.0),
            ),
            clipBehavior: Clip.antiAlias,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                CustomImage(url: _userLike[index].picture!),
                // 名称
                Padding(
                  padding: EdgeInsets.only(top: 8.0),
                  child: Text(
                    _userLike[index].name!,
                    style: TextStyle(color: Color(0xFF262626), fontSize: 13.0),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
                // 价格
                Padding(
                  padding: EdgeInsets.only(top: 8.0),
                  child: PriceWidget(price: _userLike[index].price!.toString()),
                ),
              ],
            ),
          ),
        );
      },
      staggeredTileBuilder: (int index) {
        return StaggeredTile.fit(1);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(
          '购物车',
          style: TextStyle(fontSize: 16.0, color: Color(0xFF282828)),
        ),
        backgroundColor: Colors.white,
        centerTitle: true,
        shadowColor: Colors.transparent,
        // 左侧返回箭头
        leading:
            widget.isShowBack
                ? IconButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  icon: Image.asset('assets/appbar_fanhui.png'),
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                )
                : Container(),
      ),
      body:
          !_isShowLoading
              ? Column(
                children: [
                  Expanded(
                    child: Container(
                      padding: EdgeInsets.symmetric(horizontal: 10.0),
                      child: CustomRefresher(
                        controller: _refreshController,
                        enablePullUp: false,
                        onRefresh: _loadCartDate,
                        child: CustomScrollView(
                          slivers: [
                            SliverToBoxAdapter(child: _builderCartContent()),
                            SliverToBoxAdapter(
                              child: Image.asset('assets/user_like.png'),
                            ),
                            // 猜你喜欢
                            SliverToBoxAdapter(
                              child:
                                  _userLike.length != 0
                                      ? _buildUserLike()
                                      : Container(),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  // 底部导航栏
                  _buildBottomBar(),
                ],
              )
              : LoadingAnimation(),
    );
  }
}
